﻿using System.Text.RegularExpressions;

namespace MLSMooc.Helper
{
    public static class RegularHelper
    {
        public const string MobilePattern = @"^1[3456789]\d{9}$";
        public const string EmailPattern = @"^([A-Za-z0-9_\-\.\u2E80-\u9FFF])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,8})$";

        public const string ProvIdPattern = @"\d{2}";
        public const string CityIdPattern = @"\d{4}";
        public const string CountyIdPattern = @"\d{6}";
        public const string TownIdPattern = @"\d{9}";

        public const string NumberPattern1To3 = @"\d{1,3}";
        public const string NumberPattern1To5 = @"\d{1,5}";
        public const string NumberPattern1To8 = @"\d{1,8}";
        public const string NumberPattern1To11 = @"\d{1,11}";
        public const string NumberPattern5To8 = @"\d{5,8}";

        public const string InputPattern1To10 = @"^[A-Za-z0-9()（）_\-\.\u2E80-\u9FFF]{1,10}$";
        public const string InputPattern2To20 = @"^[A-Za-z0-9()（）_\-\.\u2E80-\u9FFF]{2,20}$";
        public const string InputPattern2To50 = @"^[A-Za-z0-9()（）_\-\.\u2E80-\u9FFF]{2,50}$";

        public const string AnyPattern2To20 = @"^.{2,20}$";
        public const string AnyPattern2To50 = @"^.{2,50}$";

        public const string DatePattern = @"^20[2-9][0-9]-[0-1][0-9]-[0-3][0-9]$";

        /// <summary>
        /// 校验Sql注入
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static bool MatchSqlInjection(string inputStr)
        {
            //关键字，前或后有空格
            string pattern = @"([\s]+(and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|sqlmap|drop|-dbs))|((and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|sqlmap|drop|-dbs)[\s]+)";
            return Regex.IsMatch(inputStr, pattern, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 校验XSS攻击
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static bool MatchXSS(string inputStr)
        {
            //检验 <script></script> 标记
            string scriptPattern = @"<script[\s]*.*</script[\s]*>";
            //检验 <a>标签的 href=javascript:
            string aPattern = @"href[\s]*=[\s]*.*script[\s]*:";
            //校验on标签的事件 on=
            string onPattern = @"on[\s]*=";
            //校验iframe
            string iframePattern = @"<iframe[\s]*.*</iframe[\s]*>";
            //校验frameset
            string framesetPattern = @"<frameset[\s]*.*</frameset[\s]*>";
            string pattern = $@"({scriptPattern}|{aPattern}|{onPattern}|{iframePattern}|{framesetPattern})";
            return Regex.IsMatch(inputStr, pattern, RegexOptions.IgnoreCase);
        }
    }
}
